package client.common.interceptor;

import client.common.enums.GlobalEnums;
import client.common.pojo.ResponseMode;
import client.common.util.JWTUtilS;
import client.common.util.SerializeUtil;
import cn.hutool.jwt.JWTPayload;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 验证登录的时候是否又token
 */
@Slf4j
@Configuration
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("登录ip: {}  url {}", request.getLocalAddr(), request.getRequestURI());
        String userToken = request.getHeader("user_token");

        JWTPayload jwtPayload = JWTUtilS.parseToken(userToken);

        if (jwtPayload == null || System.currentTimeMillis() > Long.parseLong(jwtPayload.getClaim("expire_time").toString())) {
            ResponseMode r = new ResponseMode(GlobalEnums.UNLOGGED.getCode(), "Not logged in", "Not logged in");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            String encode = SerializeUtil.encode(r);
            log.info("未登录 encode: {}", encode);
            response.getWriter().write(encode);

            return false;
        }

            return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
